import { Injectable } from '@nestjs/common';
import { PrismaService } from 'src/common/prisma/PrismaService';
import ExamSubjectDto from '../dto/ExamSubjectDto';
import ServiceException from 'src/common/ServiceException';
import { plainToInstance } from 'class-transformer';
import ExamSubjectVo from '../vo/ExamSubjectVo';

/*
 * @Author: jingfuu@163.com
 * @Date: 2024-12-16 14:18:05
 * @LastEditTime: 2024-12-16 14:45:43
 * @Description: 考试科目service
 */
@Injectable()
class ExamSubjectService {
  async listAll() {
    const examSubjects = await this.prisma.examSubject.findMany({
      orderBy: { id: 'desc' },
    });
    return plainToInstance(ExamSubjectVo, examSubjects);
  }
  constructor(private prisma: PrismaService) {}
  async remove(id: number) {
    await this.prisma.examSubject.delete({ where: { id } });
  }
  async edit(data: ExamSubjectDto) {
    await this.checkExamSubjectName(data.name, data.id);
    await this.prisma.examSubject.update({
      where: { id: data.id },
      data: { name: data.name },
    });
  }
  async checkExamSubjectName(name: string, id: number) {
    const examSubject = await this.prisma.examSubject.findFirst({
      where: { name, id: { not: id } },
    });
    if (!id) {
      if (examSubject) {
        throw new ServiceException('考试科目：' + name + '已存在');
      }
    } else {
      if (examSubject && examSubject.id != id) {
        throw new ServiceException('考试科目：：' + name + '已存在');
      }
    }
  }
  async add(data: ExamSubjectDto) {
    await this.checkExamSubjectName(data.name, data.id);
    await this.prisma.examSubject.create({ data: { name: data.name } });
  }
}
export default ExamSubjectService;
